package com.example.app3;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app3.Utli.DateUtil;

import java.util.List;

public class MainActivity extends AppCompatActivity {
    //图片
    private ImageView iv_add;
    //集合
    static   ListView lv_show;
    private EditText et_name, et_phone;
    private MyAdapter myAdapter;
    private DBHelper dbHelper;
    private List<User> userList;

    private EditText title;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //添加联系人
        iv_add = findViewById(R.id.iv_add);
        //数据集合
        lv_show = findViewById(R.id.lv_show);
        //输入模糊查询的内容
        title = findViewById(R.id.tv_title);

        if (userList != null) {
            //删除
            userList.clear();
        }
        //创建数据库对象
        dbHelper = new DBHelper(MainActivity.this, "user.db", null, 1);
        //先查询数据，再把数据放到listvive标签中，进行展示
        updateListView();
        //点击添加联系人按钮,注意点击一下按钮和长点按钮他们的区别
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //添加数据
                // addData();

                addDatatext();
            }
        });
        //长按联系人进行修改
        lv_show.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //修改数据
                //updateData(position);
                 updateDatatext(position);
            }
        });
        //长按联系人进行删除
        lv_show.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //删除数据
                deleteData(position);
                return true;
            }
        });

        //进行模糊查询
        title.addTextChangedListener(new TextWatcher() {
            //输入前
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            //输入中进行搜索
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //模糊查询使用满足条件的数据
                likeListView(title.getText().toString());
            }

            //输入后进行搜索
            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }


    /**
     * 添加联系人信息
     */
    private void addDatatext() {

        Intent intent = new Intent(getApplicationContext(), textActivity.class);

        startActivity(intent);
    }


    /**
     * 添加联系人信息
     */
    private void addData() {

        //指定在那个页面的上面弹出
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        //把要弹窗页面的封装到View
        View dialogView = View.inflate(MainActivity.this, R.layout.dialog, null);
        //指定标题的一个图片
        builder.setIcon(R.drawable.icon)
                //设置标题
                .setTitle("请输入你要添加的内容")
                //设置页面
                .setView(dialogView);

        //这里是在页面加了一个确定按钮，点击确定是一个事件
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        et_name = dialogView.findViewById(R.id.et_name);
                        //  et_phone=dialogView.findViewById(R.i.et_pwd);
                        String name = et_name.getText().toString();
                        //  String phone=et_phone.getText().toString();

                        //根据名字进行查询数据
                        User user = dbHelper.get(name);
                        //判断当前用户名是否存在
                        if (user.getName() == null) {
                            //不存在的话进行添加操作

                            if (dbHelper.insert(name, DateUtil.getNowTime())) {
                                showToast("添加成功");
                                //添加完成后重新查询
                                updateListView();
                            } else {
                                showToast("添加失败");
                            }
                        } else {
                            showToast("该信息已存在");
                        }

                    }
                })
                //在添加联系人时，点击取消
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //取消当前弹出的页面
                        dialog.dismiss();
                    }
                });

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }


    /**
     * 删除联系人
     *
     * @param position
     */
    private void deleteData(int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setIcon(R.drawable.icon)
                .setTitle("提示")
                .setMessage("是否删除该编辑信息？")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        User user = (User) myAdapter.getItem(position);
                        String deleteId = user.getId();
                        if (dbHelper.delete(deleteId)) {
                            updateListView();
                            showToast("删除成功");
                        } else {
                            showToast("删除失败");
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }


    private void updateDatatext(int position) {
        User user = (User) myAdapter.getItem(position);

        Intent intent = new Intent(getApplicationContext(), textActivity.class);
        Bundle bundle = new Bundle();

        bundle.putInt("dd",position);
        bundle.putString("name",user.getName());
        bundle.putString("id",user.getId());

        intent.putExtras(bundle);

        startActivity(intent);
    }

    /**
     * 修改联系人
     *
     * @param position
     */
    private void updateData(int position) {
        View dialogView = View.inflate(MainActivity.this, R.layout.dialog, null);
        User user = (User) myAdapter.getItem(position);
        et_name = dialogView.findViewById(R.id.et_name);
        //  et_phone = dialogView.findViewById(R.id.et_pwd);
        et_name.setText(user.getName());
        //et_phone.setText(user.getPhone());
        String findId = user.getId();
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setIcon(R.drawable.icon)
                .setTitle("请修改你的内容")
                .setView(dialogView)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String name = et_name.getText().toString();
                        // String phone = et_phone.getText().toString();

                        User user = dbHelper.get(name);
                        if (user.getName() == null) {
                            if (dbHelper.update(findId, name, DateUtil.getNowTime())) {
                                showToast("修改成功");
                                updateListView();
                            } else {
                                showToast("修改失败");
                            }
                        } else {
                            showToast("该信息已存在");
                        }

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 查询出所有联系人，最后到MainActivity页面进行展示
     *
     * @param
     */
    public void updateListView() {
        //查询数据库中的所有数据
        userList = dbHelper.query();
        myAdapter = new MyAdapter(userList, MainActivity.this);
        //把封装好的数据展示到标签listVine中
        lv_show.setAdapter(myAdapter);
    }


    /**
     * 模糊查询出所有联系人，最后到MainActivity页面进行展示
     *
     * @param
     */
    public void likeListView(String tlle) {
        //查询数据库中的所有数据
        userList = dbHelper.likequery(tlle);
        myAdapter = new MyAdapter(userList, MainActivity.this);
        //把封装好的数据展示到标签listVine中
        lv_show.setAdapter(myAdapter);
    }

    public void showToast(String msg) {
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
    }
}